package com.example.messengerapp

import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.viewpager2.widget.ViewPager2
import com.example.messengerapp.databinding.ActivityMainBinding
import com.example.messengerapp.ui.ViewPagerAdapter
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import org.koin.android.ext.koin.androidContext
import org.koin.core.context.startKoin

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Инициализация Koin
        startKoin {
            androidContext(this@MainActivity)
            modules(com.example.messengerapp.ui.appModule)
        }

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // Настройка навигации и ActionBar
        val navHostFragment =
            supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
        val navController = navHostFragment.navController
        val appBarConfiguration = AppBarConfiguration(setOf(R.id.chatListFragment, R.id.usersFragment))
        setupActionBarWithNavController(navController, appBarConfiguration)

        // Настройка TabLayout и ViewPager2 для переключения между фрагментами
        val viewPager: ViewPager2 = binding.viewPager
        val tabLayout: TabLayout = binding.tabLayout
        val adapter = ViewPagerAdapter(this)
        viewPager.adapter = adapter

        val tabTitles = arrayOf("Чаты", "Пользователи")

        TabLayoutMediator(tabLayout, viewPager) { tab, position ->
            tab.text = tabTitles[position]
            tab.contentDescription = tabTitles[position]
        }.attach()
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.main_menu, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.action_edit_profile -> {
                val navController = findNavController(R.id.nav_host_fragment)
                navController.navigate(R.id.action_global_editProfileFragment)
                true
            }

            R.id.action_info -> {
                // Показать информацию о приложении
                showAppInformationDialog()
                true
            }

            R.id.action_logout -> {
                logout()
                true
            }

            else -> super.onOptionsItemSelected(item)
        }
    }

    private fun logout() {
        val auth = Firebase.auth
        auth.signOut()

        // После успешного выхода выполнить навигацию
        navigateToWelcomeFragment()
    }

    private fun navigateToWelcomeFragment() {
        try {
            val navController = findNavController(R.id.nav_host_fragment)
            navController.navigate(R.id.action_global_welcomeFragment)
        } catch (e: IllegalStateException) {
            // Обработка исключения, если контекст уже не действителен
            e.printStackTrace()
        }
    }


    private fun showAppInformationDialog() {
        val infoText = "Дипломное приложение по курсу Андроид-разработчик Urban University"

        AlertDialog.Builder(this)
            .setTitle("Информация о приложении")
            .setMessage(infoText)
            .setPositiveButton("OK", null)
            .show()
    }

    override fun onSupportNavigateUp(): Boolean {
        val navController = findNavController(R.id.nav_host_fragment)
        return navController.navigateUp() || super.onSupportNavigateUp()
    }
}
